<?php
/**
 * S3云存储插件 - 简化管理界面
 * 
 * @package CommonCloudStorage
 * @author xiaogg
 * @version 1.0
 */

require '../../../zb_system/function/c_system_base.php';
require '../../../zb_system/function/c_system_admin.php';

$zbp->Load();

// 权限检查
if (!$zbp->CheckRights('root')) {
    $zbp->ShowError(6);
    die();
}

// 加载插件配置
if (!function_exists('CommonCloudStorage_GetConfig')) {
    require_once 'include.php';
}

// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'save_config':
                $config = array(
                    'enable_sync' => isset($_POST['enable_sync']) ? 1 : 0,
                    'storage_type' => $_POST['storage_type'] ?? 'AWS',
                    'access_key' => $_POST['access_key'] ?? '',
                    'secret_key' => $_POST['secret_key'] ?? '',
                    'bucket_name' => $_POST['bucket_name'] ?? '',
                    'bucket_domain' => $_POST['bucket_domain'] ?? '',
                    'custom_domain' => $_POST['custom_domain'] ?? '',
                    'region' => $_POST['region'] ?? 'us-east-1',
                    'endpoint' => $_POST['endpoint'] ?? '',
                    'directory' => $_POST['directory'] ?? ''
                );
                
                CommonCloudStorage_SaveConfig($config);
                $message = '<div class="hint-good">配置保存成功！</div>';
                break;
                
            case 'test_connection':
                $config = CommonCloudStorage_GetConfig();
                $result = CommonCloudStorage_TestConnection($config);
                
                if ($result['success']) {
                    $message = '<div class="hint-good">连接测试成功：' . htmlspecialchars($result['message']) . '</div>';
                } else {
                    $message = '<div class="hint-bad">连接测试失败：' . htmlspecialchars($result['message']) . '</div>';
                }
                break;
                
            case 'batch_replace':
                $replace_type = $_POST['replace_type'] ?? 'to_custom';
                $result = CommonCloudStorage_BatchReplaceUrls($replace_type);
                
                if ($result['success']) {
                    $message = '<div class="hint-good">批量替换成功，共处理 ' . $result['count'] . ' 条记录</div>';
                } else {
                    $message = '<div class="hint-bad">批量替换失败：' . htmlspecialchars($result['message']) . '</div>';
                }
                break;
        }
    }
}

$config = CommonCloudStorage_GetConfig();

?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>S3云存储插件管理</title>
    <link rel="stylesheet" type="text/css" href="style.css">
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; background-color: #f5f5f5; }
        .container { max-width: 1200px; margin: 0 auto; background-color: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
        .header { text-align: center; margin-bottom: 30px; padding-bottom: 20px; border-bottom: 2px solid #007cba; }
        .section { margin-bottom: 30px; padding: 20px; border: 1px solid #ddd; border-radius: 6px; }
        .section h3 { margin-top: 0; color: #007cba; }
        .form-group { margin-bottom: 15px; }
        .form-group label { display: inline-block; width: 150px; font-weight: bold; }
        .form-group input, .form-group select { width: 300px; padding: 8px; border: 1px solid #ddd; border-radius: 4px; }
        .form-group .note { display: block; margin-left: 150px; font-size: 12px; color: #666; margin-top: 5px; }
        .btn { background-color: #007cba; color: white; padding: 10px 20px; border: none; border-radius: 4px; cursor: pointer; margin-right: 10px; }
        .btn:hover { background-color: #005a87; }
        .btn-test { background-color: #28a745; }
        .btn-test:hover { background-color: #218838; }
        .btn-danger { background-color: #dc3545; }
        .btn-danger:hover { background-color: #c82333; }
        .hint-good { background-color: #d4edda; color: #155724; padding: 10px; border: 1px solid #c3e6cb; border-radius: 4px; margin-bottom: 20px; }
        .hint-bad { background-color: #f8d7da; color: #721c24; padding: 10px; border: 1px solid #f5c6cb; border-radius: 4px; margin-bottom: 20px; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>S3云存储插件管理</h1>
            <p>支持AWS S3协议、FTP及各大云服务商对象存储的文件同步插件</p>
        </div>

        <?php if (isset($message)) echo $message; ?>

        <!-- 基本配置 -->
        <div class="section">
            <h3>基本配置</h3>
            <form method="post">
                <input type="hidden" name="action" value="save_config">
                
                <div class="form-group">
                    <label>开启同步：</label>
                    <input type="checkbox" name="enable_sync" value="1" <?php echo $config['enable_sync'] ? 'checked' : ''; ?>>
                    <span class="note">勾选后将直接上传文件到云存储，不在本地保存</span>
                </div>

                <div class="form-group">
                    <label>签名固定值：</label>
                    <select name="storage_type">
                        <option value="AWS" <?php echo $config['storage_type'] == 'AWS' ? 'selected' : ''; ?>>AWS S3协议</option>
                        <option value="FTP" <?php echo $config['storage_type'] == 'FTP' ? 'selected' : ''; ?>>FTP空间</option>
                    </select>
                    <span class="note">选择存储类型，AWS适用于各大云服务商对象存储</span>
                </div>

                <div class="form-group">
                    <label>密钥Access Key：</label>
                    <input type="text" name="access_key" value="<?php echo htmlspecialchars($config['access_key']); ?>">
                    <span class="note">访问凭证密钥，FTP模式下为用户名</span>
                </div>

                <div class="form-group">
                    <label>密钥Secret Key：</label>
                    <input type="password" name="secret_key" value="<?php echo htmlspecialchars($config['secret_key']); ?>">
                    <span class="note">访问凭证密钥，FTP模式下为密码</span>
                </div>

                <div class="form-group">
                    <label>存储桶空间名：</label>
                    <input type="text" name="bucket_name" value="<?php echo htmlspecialchars($config['bucket_name']); ?>">
                    <span class="note">存储桶名称，FTP模式下为IP地址</span>
                </div>

                <div class="form-group">
                    <label>存储桶访问域名：</label>
                    <input type="text" name="bucket_domain" value="<?php echo htmlspecialchars($config['bucket_domain']); ?>">
                    <span class="note">存储桶默认域名，FTP模式下留空</span>
                </div>

                <div class="form-group">
                    <label>自定义地址：</label>
                    <input type="text" name="custom_domain" value="<?php echo htmlspecialchars($config['custom_domain']); ?>">
                    <span class="note">自定义绑定域名，留空则使用当前网站地址</span>
                </div>

                <div class="form-group">
                    <label>区域设置：</label>
                    <input type="text" name="region" value="<?php echo htmlspecialchars($config['region']); ?>">
                    <span class="note">存储区域，如：us-east-1、ap-beijing等（S3模式必需，FTP模式留空）</span>
                </div>

                <div class="form-group">
                    <label>自定义端点：</label>
                    <input type="text" name="endpoint" value="<?php echo htmlspecialchars($config['endpoint']); ?>">
                    <span class="note">自定义API端点，留空则自动构建（如：https://s3.amazonaws.com）</span>
                </div>

                <div class="form-group">
                    <label>目录参数：</label>
                    <input type="text" name="directory" value="<?php echo htmlspecialchars($config['directory']); ?>">
                    <span class="note">可为空，填写时在返回URL的域名后拼接此目录</span>
                </div>

                <div class="form-group">
                    <button type="submit" class="btn">保存配置</button>
                </div>
            </form>
        </div>

        <!-- 连接测试 -->
        <div class="section">
            <h3>连接测试</h3>
            <form method="post">
                <input type="hidden" name="action" value="test_connection">
                <p>点击下方按钮测试当前配置是否正确</p>
                <button type="submit" class="btn btn-test">测试连接</button>
            </form>
        </div>

        <!-- 批量操作 -->
        <div class="section">
            <h3>批量替换附件地址</h3>
            <form method="post" onsubmit="return confirm('确定要批量替换吗？此操作不可逆！');">
                <input type="hidden" name="action" value="batch_replace">
                
                <div class="form-group">
                    <label>替换类型：</label>
                    <select name="replace_type">
                        <option value="to_custom">替换为自定义地址</option>
                        <option value="to_local">替换为本站地址</option>
                    </select>
                    <span class="note">批量替换数据库中文章的附件地址</span>
                </div>

                <div class="form-group">
                    <button type="submit" class="btn btn-danger">开始替换</button>
                </div>
            </form>
        </div>

        <!-- 配置示例 -->
        <div class="section">
            <h3>配置示例</h3>
            <h4>腾讯云COS</h4>
            <ul>
                <li>签名固定值：AWS S3协议</li>
                <li>Access Key：SecretId</li>
                <li>Secret Key：SecretKey</li>
                <li>存储桶空间名：bucket-name</li>
                <li>存储桶访问域名：bucket-name.cos.region.myqcloud.com</li>
                <li>区域设置：ap-beijing</li>
                <li>自定义端点：留空（或填写：https://cos.ap-beijing.myqcloud.com）</li>
            </ul>

            <h4>阿里云OSS</h4>
            <ul>
                <li>签名固定值：AWS S3协议</li>
                <li>Access Key：AccessKeyId</li>
                <li>Secret Key：AccessKeySecret</li>
                <li>存储桶空间名：bucket-name</li>
                <li>存储桶访问域名：bucket-name.oss-region.aliyuncs.com</li>
                <li>区域设置：oss-cn-hangzhou</li>
                <li>自定义端点：留空（或填写：https://oss-cn-hangzhou.aliyuncs.com）</li>
            </ul>

            <h4>FTP空间</h4>
            <ul>
                <li>签名固定值：FTP空间</li>
                <li>Access Key：FTP用户名</li>
                <li>Secret Key：FTP密码</li>
                <li>存储桶空间名：192.168.1.100:21</li>
                <li>存储桶访问域名：留空</li>
                <li>区域设置：留空</li>
            </ul>
        </div>
    </div>
</body>
</html>

<?php

/**
 * 测试连接函数
 */
function CommonCloudStorage_TestConnection($config) {
    if (empty($config['access_key']) || empty($config['secret_key']) || empty($config['bucket_name'])) {
        return array('success' => false, 'message' => '请先完善配置信息');
    }
    
    if ($config['storage_type'] === 'FTP') {
        return CommonCloudStorage_FTP_Test($config);
    } else {
        return CommonCloudStorage_S3_Test($config);
    }
}

/**
 * 批量替换URL函数
 */
function CommonCloudStorage_BatchReplaceUrls($replace_type) {
    global $zbp;
    
    $config = CommonCloudStorage_GetConfig();
    $count = 0;
    
    try {
        // 获取所有文章
        $sql = "SELECT * FROM " . $zbp->table['Post'] . " WHERE log_Type = 0";
        $articles = $zbp->GetListType('Post', $sql);
        
        foreach ($articles as $article) {
            $content = $article->Content;
            $intro = $article->Intro;
            $updated = false;
            
            if ($replace_type === 'to_custom') {
                // 替换为自定义地址
                $domain = $config['custom_domain'] ?: $zbp->host;
                $pattern = '/(' . preg_quote($zbp->host, '/') . ')([^"\'>\s]+\.(jpg|jpeg|png|gif|webp|bmp))/i';
                $replacement = $domain . '$2';
            } else {
                // 替换为本站地址
                $custom_domain = $config['custom_domain'] ?: $config['bucket_domain'];
                if ($custom_domain) {
                    $pattern = '/(' . preg_quote($custom_domain, '/') . ')([^"\'>\s]+\.(jpg|jpeg|png|gif|webp|bmp))/i';
                    $replacement = $zbp->host . '$2';
                } else {
                    continue;
                }
            }
            
            $new_content = preg_replace($pattern, $replacement, $content);
            $new_intro = preg_replace($pattern, $replacement, $intro);
            
            if ($new_content !== $content || $new_intro !== $intro) {
                $article->Content = $new_content;
                $article->Intro = $new_intro;
                $article->Save();
                $count++;
                $updated = true;
            }
        }
        
        return array('success' => true, 'count' => $count);
        
    } catch (Exception $e) {
        return array('success' => false, 'message' => $e->getMessage());
    }
}

?>